import pygame
from .snake import Snake
from .food import Food
from .config import *

class Game:
    def __init__(self):
        pygame.init()
        self.screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
        self.clock = pygame.time.Clock()
        self.font = pygame.font.Font(None, 36)
        self.reset()
        
    def reset(self):
        self.snake = Snake()
        self.food = Food()
        self.score = 0
        
    def handle_keys(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                return False
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    return False
                if event.key == pygame.K_UP and self.snake.direction != pygame.K_DOWN:
                    self.snake.direction = pygame.K_UP
                elif event.key == pygame.K_DOWN and self.snake.direction != pygame.K_UP:
                    self.snake.direction = pygame.K_DOWN
                elif event.key == pygame.K_LEFT and self.snake.direction != pygame.K_RIGHT:
                    self.snake.direction = pygame.K_LEFT
                elif event.key == pygame.K_RIGHT and self.snake.direction != pygame.K_LEFT:
                    self.snake.direction = pygame.K_RIGHT
        return True
    
    def update(self):
        self.snake.update()
        
        # 检查是否吃到食物
        if self.snake.get_head_position() == self.food.position:
            self.snake.length += 1
            self.score += 1
            self.food.randomize_position()
            
        # 检查是否撞到自己
        if self.snake.get_head_position() in self.snake.positions[1:]:
            self.reset()
            
    def draw(self):
        self.screen.fill(BLACK)
        self.snake.draw(self.screen)
        self.food.draw(self.screen)
        score_text = self.font.render(f'Score: {self.score}', True, WHITE)
        self.screen.blit(score_text, (5, 5))
        pygame.display.update()
        
    def run(self):
        running = True
        while running:
            running = self.handle_keys()
            self.update()
            self.draw()
            self.clock.tick(FPS)
        pygame.quit() 